'''
########################
#
# Copyright 2011, Vanderbilt University
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#       http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an "AS IS"
# BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied.  See the License for the specific languaged governing 
# permissions and limitations under the License.
#
########################


@author: Kathy Benitez

updated:June 30,2011
'''
import pickle, csv, argparse, datetime, time
import settings
import popStats, policyEvaluation

def experiment1(args):
    """
    Provided as an example of policy construction.  Evaluates the test data with respect to the Policy Gender, Race, Age, Zip, and
    reports the results.  Information about the Population Statistics Database must be provided.
    """
    dset = csv.reader(open("../data/demographics_test2.csv", 'r'))
    fields = pickle.load(open("../data/test2/fields.pckl", 'r'))
    prior = pickle.load(open("../data/test2/prior.pckl", 'r'))
    vocab = pickle.load(open("../data/test2/vocab.pckl", 'r'))
    ps = popStats.PopStatsZip(engine = args.engine, uname = args.uname, passwd = args.passwd, hostAndPort = args.hostAndPort, database = args.database)
    pc = policyEvaluation.PolicyConstructor(vocab, fields)
    e = policyEvaluation.Evaluator(vocab, fields, dset, prior, ps)

    """
    Gender, Race, Age, Zip
    
    """
    pc.makeAllSpecific()
    r = e.evaluatePolicy(pc.getPolicy())
    print "Gender, Race, Age, Zip"
    print pc.getPolicy()
    print r
    
def experiment2(args):
    """
    Evaluates the sample Adult dataset with respect to multiple pre-defined policies.  Saves the results in a 
    user-specified output file.
    """
    dset = csv.reader(open("../data/adult/dsets/adult.v3.1.11_Translated_100.csv", 'r'))
    fields = pickle.load(open("../data/adult/fields.pckl", 'r'))
    prior = pickle.load(open("../data/adult/prior.pckl", 'r'))
    vocab = pickle.load(open("../data/adult/vocab.pckl", 'r'))
    ps = popStats.PopStatsZip(engine = args.engine, uname = args.uname, passwd = args.passwd, hostAndPort = args.hostAndPort, database = args.database)
    pc = policyEvaluation.PolicyConstructor(vocab, fields)
    e = policyEvaluation.Evaluator(vocab, fields, dset, prior, ps)
    report = []
    startTime = time.time()
    
    """
    Gender, Race, Age, Zip
    
    """
    pc.makeAllSpecific()
    r = e.evaluatePolicy(pc.getPolicy())
    report.append(["Gender, Race, Age, Zip", pc.getPolicy(), r])
    """
    Gender, Race, Age
    
    """
    pc.makeAllSpecific()
    pc.makeGeneral("zip5")
    r = e.evaluatePolicy(pc.getPolicy())

    """
    Gender, Race, Zip
    """
    pc.makeAllSpecific()
    pc.makeGeneral("age")
    r = e.evaluatePolicy(pc.getPolicy())
    report.append(["Gender, Race, Zip", pc.getPolicy(), r])
    """
    Safe Harbor
    """
    pc.makeAllSpecific()
    pc.matchNCharacters("zip5", 3)
    pc.topCode("age", 89)
    r = e.evaluatePolicy(pc.getPolicy())
    report.append(["Safe Harbor", pc.getPolicy(), r])
    
    elapsedTime = time.time() - startTime
    print "Evaluated policies in %i minutes"%(elapsedTime / 60)
    out = open(args.outPath, 'w')
    o = csv.writer(out)
    o.writerows(report)
    out.close()

def timetest(args):
    """
    Utility function for determining the amount of time used to evaluate one policy.  For benchmarking.
    """
    dset = csv.reader(open("../data/adult/dsets/adult.v3.1.11_Translated_100.csv", 'r'))
    fields = pickle.load(open("../data/adult/fields.pckl", 'r'))
    prior = pickle.load(open("../data/adult/prior.pckl", 'r'))
    vocab = pickle.load(open("../data/adult/vocab.pckl", 'r'))
    ps = popStats.PopStatsZip(engine = args.engine, uname = args.uname, passwd = args.passwd, hostAndPort = args.hostAndPort, database = args.database)
    pc = policyEvaluation.PolicyConstructor(vocab, fields)
    e = policyEvaluation.Evaluator(vocab, fields, dset, prior, ps)
    report = []
    startTime = time.time()
    pc.makeAllSpecific()
    r = e.evaluatePolicy(pc.getPolicy())
    elapsedTime = time.time() - startTime
    report.append(["Gender, Race, Age, Zip", pc.getPolicy(), r, elapsedTime])
    print "Evaluated 1 policy in %i minutes"%(elapsedTime / 60)
    out = open("../data/adult/out/timetest.csv", 'w')
    o = csv.writer(out)
    o.writerows(report)
    out.close()
    
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Information is needed about the Population Statistics database')
    parser.add_argument('--e', dest='engine', default = settings.engine)
    parser.add_argument('--u', dest='uname', default = settings.uname)
    parser.add_argument('--p', dest='passwd', default = settings.passwd)
    parser.add_argument('--h', dest='hostAndPort', default = settings.hostAndPort)
    parser.add_argument('--d', dest='database', default = settings.database)
    parser.add_argument('--x', dest='experiments', default = [1])
    parser.add_argument('--o', dest='outPath', default ="../data/"+ datetime.datetime.now().strftime("%m-%d_%H:%M:%S"))
    args = parser.parse_args()
    if "1" in args.experiments:
        experiment1(args)
    elif "2" in args.experiments:
        experiment2(args)
    else:
        timetest(args)